import 'dart:async';
import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:xsdk_flutter/xsdk/framework/base/xsdk_function.dart';
import 'package:xsdk_flutter/xsdk/framework/bean/x_bean_device.dart';
import 'package:xsdk_flutter/xsdk/operation/x_constant_temp.dart';
import 'package:xsdk_flutter/xsdk/utils/bluetooth/support/x_notify_bluetooth_device_callback.dart';
import 'package:xsdk_flutter/xsdk/utils/bluetooth/api/x_ble_connect_api.dart';
import 'package:xsdk_flutter/xsdk/utils/print/base/x_utils_print_command_base.dart';
import 'package:xsdk_flutter/xsdk/utils/print/base/x_utils_print_command_tspl.dart';
import 'package:xsdk_flutter/xsdk/utils/queue/x_bean_queue_message.dart';
import 'package:xsdk_flutter/xsdk/utils/queue/x_queue.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_date.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_flutter.dart';
import 'package:xsdk_flutter/xsdk/utils/json/x_utils_json.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_log.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_share_preferences.dart';
import 'package:xsdk_flutter/xsdk/utils/x_utils_string.dart';


/*
低功耗蓝牙 bluetooth ble
https://pub.flutter-io.cn/packages/flutter_blue_plus
目前只支持android和ios

dependencies:
  flutter_blue_plus: ^1.4.0
import 'package:flutter_blue_plus/flutter_blue_plus.dart';

注意: 如果扫描没有内容,则需要设置权限
注意: ble写了数据防止丢包,主要mtu大小,数据要分包再写入;
注意:android的byte是8位的(-128~127), flutter没有byte只有int,因此没有负数, 在flutter的List<int>中,>=128的数,减256后即为对应java的byte数据,
因此base64转List<int>或String转转List<int>后的数据值是没有问题的,可直接写入

 */


abstract class XBluetoothBLEUtils{

  //扫描蓝牙设备
  static final List<XBaseDevice> _scanBluetoothBLEDevicesList=[];
  //连接的蓝牙设备conn
  static final Set<XBleConnectApi> bleConnectApiList={};
  //连接设备
  static final Set<XBaseDevice> bluetoothBLEDeviceList={};
  //消息队列
  static XQueue? _queue;

  static final XBaseQueueMessage _heartbeatMsg=XBaseQueueMessage(
    msgId: 'ble_heartbeat_${XDateUtils.getCurrentTime_ms()}',
    isPriorityHandle:true,
    isHeartbeatCommand:true,
  );

  /*
  1.初始化 ok(注意:不能在app中初始化,因为sp初始化没完成,导致获取设备记录为空)
  注意:
  1.1.如果使用多用户保存:
  则需要登录后更新用户组:XSharePreferencesUtils.saveString(XConstants.SP_UserGroup,XXX);
  然后再初始化;切换用户或company时,则需要重新初始化
  1.2.如果不启用多用户,则可在欢迎界面初始化;
   */
  static void init(){
    if(!XFlutterUtils.isAndroidOriOSSystem()){
      XLogUtils.printLog('---非 Android/iOS 平台,不支持此蓝牙BLE库!');
      return;
    }

    // turn on bluetooth ourself if we can
    // for iOS, the user controls bluetooth enable/disable
    // if (XFlutterUtils.isAndroid()) {
    //   FlutterBluePlus.turnOn();
    // }

    //断开所有连接(用于重新初始化)
    for(XBleConnectApi bleApi in bleConnectApiList){
      bleApi.xRelease();
    }
    //
    _scanBluetoothBLEDevicesList.clear();
    bleConnectApiList.clear();
    bluetoothBLEDeviceList.clear();

    //1.连接设备
    String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
    String connectDeviceJson=XSharePreferencesUtils.getString('$userGroup${XConstants.SP_BluetoothBleDevicesList}');

    if(!XStringUtils.isEmpty(connectDeviceJson)){
      List<dynamic> list=XJsonUtils.json2List(connectDeviceJson);
      for(dynamic item in list){
        bluetoothBLEDeviceList.add(XBaseDevice.fromJson(item));
      }
    }

    XLogUtils.printLog('---设备ble记录数=${bluetoothBLEDeviceList.length}');

    //2.连接所有设备
    for(XBaseDevice baseDevice in bluetoothBLEDeviceList){
      if(baseDevice.isEnable){
        _connectDevice(baseDevice);
      }
    }

    //3.启动消息队列
    _queue??=XQueue(
        queueName: 'XBluetoothBLEUtilsQueue',
        isEnableHeartBeat:true, //启动心跳包(自动重连)
        isConcurrentMode:true, //这里要设置并发(不按顺序,否则打印失败,这重新打印再次卡住不能往下打印)
        heartbeatTime: 10,
        notifyHandleMsg: (XBaseQueueMessage msg) async{
          //接收到队列消息通知,取出消息并写入蓝牙设备(这里不需要再开线程,已在线程内) ok
          try{

            if (msg.isHeartbeatCommand){
              //心跳包, 输出到所有蓝牙设备,遍历当前移动设备连接的蓝牙设备
              for(XBleConnectApi bleApi in bleConnectApiList){

                XBaseDevice baseDevice=bleApi.baseDevice;
                msg.deviceName=bleApi.baseDevice.deviceName;
                msg.bluetoothAddress=bleApi.baseDevice.bluetoothAddress;

                XLogUtils.printLog('---开始发送蓝牙心跳包数据到: ${bleApi.bluetoothAddress}',tag: 'XOther');

                if (baseDevice.printCommandType==0){
                  //属于ESC命令
                  msg.message_Uint8List=XBasePrintCommandUtils.command_heartbeatPacket_esc;
                }else if (baseDevice.printCommandType==1){
                  //属于TSPL命令
                  msg.message_Uint8List=XBasePrintCommandUtils.command_heartbeatPacket_tspl;
                }else if (baseDevice.printCommandType==2){
                  //属于CPCL命令
                  msg.message_Uint8List=XBasePrintCommandUtils.command_heartbeatPacket_cpcl;
                }

                //写入心跳
                bleApi.writeMsg(msg,characteristicId:msg.characteristicId);
              }

              _handleWriteBluetoothDeviceSucceed(msg.deviceName,msg.bluetoothAddress,msg);

            }else if (msg.isOpenCashDrawerCommand){
              //打开钱箱

              //输出到所有蓝牙设备,遍历当前移动设备连接的蓝牙设备
              for(XBleConnectApi bleApi in bleConnectApiList){

                XBaseDevice baseDevice=bleApi.baseDevice;
                msg.deviceName=bleApi.baseDevice.deviceName;
                msg.bluetoothAddress=bleApi.baseDevice.bluetoothAddress;

                //
                XLogUtils.printLog('---开始发送打开钱箱命令到: ${bleApi.bluetoothAddress}');

                if (baseDevice.printCommandType==0){
                  //属于ESC命令
                  msg.message_Uint8List=XBasePrintCommandUtils.command_openCashDrawer_esc;
                }else if (baseDevice.printCommandType==1){
                  //属于TSPL命令
                  msg.message=XBaseTSPLPrintCommandUtils.getPrintCommand_TSPL(XBaseTSPLPrintCommandUtils.PrintCommand_TSPL_openCash,null);
                }else if (baseDevice.printCommandType==2){
                  //属于CPCL命令...
                }

                //打开钱箱
                bleApi.writeMsg(msg,characteristicId:msg.characteristicId);
              }

              _handleWriteBluetoothDeviceSucceed(msg.deviceName,msg.bluetoothAddress,msg);

            }else{

              bool isWriteSucceed=false;

              //1.以指定蓝牙设备address为优先
              if (!XStringUtils.isEmpty(msg.bluetoothAddress)){

                for(XBleConnectApi bleApi in bleConnectApiList) {
                  if(bleApi.bluetoothAddress==msg.bluetoothAddress){
                    //写入数据
                    isWriteSucceed= await bleApi.writeMsg(msg,characteristicId:msg.characteristicId,isMTULongWrite:bleApi.baseDevice.isMTULongWrite);
                    break;
                  }
                }

              }else if(msg.deviceScene!=null){
                //2.指定蓝牙设备或场景,获得对应对应的蓝牙设备(可能有多个)

                //消息是否有设备序号
                String? serialNumber=msg.deviceSerialNumber;

                //遍历当前移动设备连接的蓝牙设备和场景属性(可能有多个合适,只要其中一个打印成功,则认为该消息成功)
                for(XBleConnectApi bleApi in bleConnectApiList){
                  XBaseDevice baseDevice=bleApi.baseDevice;
                  List<XBaseDeviceScene>? scenes=baseDevice.scenes;
                  if(scenes!=null && scenes.isNotEmpty){
                    for(XBaseDeviceScene itemScene in scenes){
                      if(msg.deviceScene==itemScene){
                        if(!XStringUtils.isEmpty(serialNumber)){
                          //消息存在指定设备序号,再以场景+序号判断
                          if(serialNumber==baseDevice.serialNumber){
                            //写入数据
                            bool isWriteStatus = await bleApi.writeMsg(msg,characteristicId:msg.characteristicId,isMTULongWrite:baseDevice.isMTULongWrite);
                            if(isWriteStatus){
                              isWriteSucceed=true;
                            }
                          }
                        }else{
                          //消息的场景没有指定设备序号,即以场景判断即可
                          //写入数据
                          bool isWriteStatus = await bleApi.writeMsg(msg,characteristicId:msg.characteristicId,isMTULongWrite:baseDevice.isMTULongWrite);
                          //
                          if(isWriteStatus){
                            isWriteSucceed=true;
                          }
                        }
                        break;
                      }
                    }
                  }
                }
              }

              if (isWriteSucceed){
                _handleWriteBluetoothDeviceSucceed(msg.deviceName,msg.bluetoothAddress,msg);
              }else{
                //写入失败,处理写入消息失败
                _handleWriteBluetoothDeviceFailed(msg.deviceName,msg.bluetoothAddress,"没有可用蓝牙设备",msg);
              }

            }

          }catch(e){
            XLogUtils.printLog('---蓝牙设备写入出错,bluetoothAddress= ${msg.bluetoothAddress}, $e');
            //处理写入消息失败
            _handleWriteBluetoothDeviceFailed(msg.deviceName,msg.bluetoothAddress,"蓝牙设备写入发生出错",msg);
          }
        },
        notifyTempMsgQueueIdleAndMsgQueueHasItem: () {
          //...
          //XLogUtils.printLog('---ble notifyTempMsgQueueIdleAndMsgQueueHasItem');
        },
        notifyHandleHeartbeat: () {
          //接收到心跳包通知 ok
          XLogUtils.printLog('---XBluetoothBLEUtils,间隔${_queue?.heartbeatTime}秒收到处理XQueue心跳包',tag: 'XOther');
          if(bleConnectApiList.isEmpty){
            return;
          }

          //心跳包命令(esc/tspl),按蓝牙设备的命令类型决定,同时实现自动重连
          sendMsgToQueue(_heartbeatMsg);

        }
    );

    //初始化队列
    _queue?.init();

  }

  //2.释放ok
  static void clean(){
    //
    try{
      _queue?.xRelease();
      //断开所有连接
      for(XBleConnectApi bleApi in bleConnectApiList){
        bleApi.xRelease();
      }
      //
      bleConnectApiList.clear();
      _scanBluetoothBLEDevicesList.clear();
      bluetoothBLEDeviceList.clear();
    }catch(e){
      XLogUtils.printLog('---bleUtils clean报错: $e');
    }

  }


  //3.扫描设备ok
  static Timer? _scanTimer;
  static void scanDevices (
      {
        required XFunctionNotifyScanFinish<XBaseDevice> notifyScanFinish,
        int scanTime_s=5,
      }
      ) async
  {
    try{
      if(!XFlutterUtils.isAndroidOriOSSystem()){
        XLogUtils.printLog('---非 Android/iOS 平台,不支持此蓝牙BLE库!');
        return;
      }

      //
      _scanBluetoothBLEDevicesList.clear();

      //使用Timer,可手动取消延时任务,替代Future.delayed()
      if(_scanTimer!=null&&_scanTimer!.isActive){
        XLogUtils.printLog('---_scanTimer取消');
        _scanTimer!.cancel();
        //停止扫描
        await FlutterBluePlus.stopScan();
      }

      //开始扫描
      FlutterBluePlus.scanResults
          .listen(
              (List<ScanResult> results)
          {
            // do something with scan results
            for (ScanResult r in results) {
              if(!XStringUtils.isEmpty(r.device.platformName)){
                //支持ble
                XBaseDevice scanDevice=XBaseDevice(deviceName: r.device.platformName,bluetoothAddress: r.device.remoteId.str);
                if(!_scanBluetoothBLEDevicesList.contains(scanDevice)){
                  XLogUtils.printLog('---scan device: ${r.device.platformName}, address=${r.device.remoteId.str}, serviceUuids= ${r.advertisementData.serviceUuids}');
                  _scanBluetoothBLEDevicesList.add(XBaseDevice(deviceName: r.device.platformName,bluetoothAddress: r.device.remoteId.str));
                }
              }
            }
          });
      FlutterBluePlus.startScan(timeout: Duration(seconds: scanTime_s))
          .whenComplete(
              ()
          {
            XLogUtils.printLog('---扫描完成回调通知');
          }
      );

      //
      _scanTimer = Timer(
          Duration(seconds: scanTime_s),
              () {
            //停止扫描
            FlutterBluePlus.stopScan();
            //通知扫描完成
            notifyScanFinish(_scanBluetoothBLEDevicesList);
          }
      );

    }catch(e){
      XLogUtils.printLog('e: $e');
    }

  }

  //4.手动停止扫描(如:退出当前扫描界面) ok
  static Future stopScan() async{
    try{
      if(_scanTimer!=null&&_scanTimer!.isActive){
        XLogUtils.printLog('---_scanTimer取消');
        _scanTimer!.cancel();
      }

      // FlutterBluePlus.instance.isScanning.listen((bool isScanning) {
      //   if(isScanning){
      //     XLogUtils.printLog('---正在扫描,手动停止');
      //     FlutterBluePlus.instance.stopScan();
      //   }else{
      //     XLogUtils.printLog('---不是正在扫描');
      //   }
      // });

      //实测可直接调用(即是已经停止扫描也可调用)
      FlutterBluePlus.stopScan();

    }catch(e){
      //XLogUtils.printLog('---停止扫描报错: $e');
    }
  }


  //5.添加设备记录和连接ok
  static void addDevice(XBaseDevice baseDevice){

    try{

      if(!XFlutterUtils.isAndroidOriOSSystem()){
        XLogUtils.printLog('---非 Android/iOS 平台,不支持此蓝牙BLE库!');
        return;
      }

      //1.保存连接设备记录
      XLogUtils.printLog('---添加设备记录');
      if(!bluetoothBLEDeviceList.contains(baseDevice)){
        //
        bluetoothBLEDeviceList.add(baseDevice);
        //XLogUtils.printLog("---当前设备数:${connectedDeviceList.length}");
        String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
        XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_BluetoothBleDevicesList}', XJsonUtils.obj2Json(bluetoothBLEDeviceList));

        //2.连接设备
        _connectDevice(baseDevice);
      }else{
        XLogUtils.printLog('---添加设备已存在');
      }


    }catch(e){
      XLogUtils.printLog('addDevice报错: $e');
    }

  }

  //6.更新设备设置 ok
  static void updateDevice(XBaseDevice device){
    try{
      for(XBaseDevice deviceItem in bluetoothBLEDeviceList){
        if(device==deviceItem){
          deviceItem.nickName=device.nickName;
          deviceItem.brand=device.brand;
          deviceItem.deviceKey=device.deviceKey;
          deviceItem.isConnected=device.isConnected;
          deviceItem.isUserSelect=device.isUserSelect;
          deviceItem.isEnable=device.isEnable;
          deviceItem.serialNumber=device.serialNumber;
          deviceItem.customType=device.customType;
          deviceItem.scenes=device.scenes;
          deviceItem.printCommandType=device.printCommandType;
          deviceItem.printTypeName=device.printTypeName;
          deviceItem.printerPagerSize=device.printerPagerSize;
          deviceItem.printerDPI=device.printerDPI;
          deviceItem.printerLabelSizeWidth=device.printerLabelSizeWidth;
          deviceItem.printerLabelSizeHeight=device.printerLabelSizeHeight;
          deviceItem.isGBK=device.isGBK;
          deviceItem.isReceiveDeviceMsg=device.isReceiveDeviceMsg;
          deviceItem.characteristicIds=device.characteristicIds;
          deviceItem.isMTULongWrite=device.isMTULongWrite;
          break;
        }
      }

      //更新保存
      String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
      XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_BluetoothBleDevicesList}', XJsonUtils.obj2Json(bluetoothBLEDeviceList));

    }catch(e){
      XLogUtils.printLog('updateDevice报错: $e');
    }


  }


  //7.1.移除设备并删除记录 ok
  static void removeDevice(String address){

    try{
      //1.断开和删除连接
      bleConnectApiList.removeWhere((XBleConnectApi bleApi) {
        if(bleApi.bluetoothAddress==address){
          bleApi.xRelease();
          return true;
        }else{
          return false;
        }
      });

      //2.移除设备记录
      bluetoothBLEDeviceList.removeWhere((XBaseDevice element){
        if(address==element.bluetoothAddress){
          return true;
        }else{
          return false;
        }
      });

      //更新保存
      String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
      XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_BluetoothBleDevicesList}', XJsonUtils.obj2Json(bluetoothBLEDeviceList));

    }catch(e){
      //
    }

  }

  //7.2.删除设备by customType
  static void removeDeviceByType(String deviceCustomType){

    try{
      //1.断开和删除连接
      bleConnectApiList.removeWhere((XBleConnectApi bleApi) {
        if(bleApi.baseDevice.customType==deviceCustomType){
          bleApi.xRelease();
          return true;
        }else{
          return false;
        }
      });

      //2.移除设备记录
      bluetoothBLEDeviceList.removeWhere((XBaseDevice element){
        if(deviceCustomType==element.customType){
          return true;
        }else{
          return false;
        }
      });

      //更新保存
      String userGroup=XSharePreferencesUtils.getString(XConstants.SP_UserGroup);//多用户保存
      XSharePreferencesUtils.saveString('$userGroup${XConstants.SP_BluetoothBleDevicesList}', XJsonUtils.obj2Json(bluetoothBLEDeviceList));

    }catch(e){
      //
    }
  }


  //8.1发送消息(用于测试打印) ok
  static void sendMsgToDevice_test(
      {
        required String bluetoothAddress,
        required String text,
        String? characteristicId,//指定特征值Id
      }
      ) async
  {

    //
    XBaseQueueMessage msg=XBaseQueueMessage(msgId: 'ble_test_${XDateUtils.getCurrentTime_ms()}',message: text);
    msg.bluetoothAddress=bluetoothAddress;
    msg.characteristicId=characteristicId;

    try{
      //
      bool isWriteSucceed=false;
      for(XBleConnectApi item in bleConnectApiList){
        if(item.bluetoothAddress==bluetoothAddress){
          isWriteSucceed= await item.writeMsg(msg,characteristicId:msg.characteristicId,isMTULongWrite:item.baseDevice.isMTULongWrite);
          break;
        }
      }

      //成功交由写入方法中处理,
      if(isWriteSucceed){
        XLogUtils.printLog('---打印测试成功');
      }else{
        XLogUtils.printLog('---打印测试失败');
      }

    }catch(e){
      XLogUtils.printLog('---打印测试失败 error: $e');
    }
  }

  //8.2发送消息(添加到队列处理,适用多端打印)ok
  static void sendMsgToQueue(XBaseQueueMessage msg){
    try{
      _queue?.addNewMsgToQueueForWaitQueueAutoHandle(msg);
    }catch(e){
      XLogUtils.printLog('---sendMsgToQueue报错: $e');
    }
  }


  //9.添加各种监听
  //添加BLE蓝牙设备连接状态监听
  static void addBleDeviceConnectListener(XFunctionBleDeviceConnectListener? listener){
    XBluetoothDeviceNotifyCallback.instance.addBleDeviceConnectListener(listener);
  }
  //删除BLE蓝牙设备连接状态监听
  static void removeBleDeviceConnectListener(XFunctionBleDeviceConnectListener? listener){
    XBluetoothDeviceNotifyCallback.instance.removeBleDeviceConnectListener(listener);
  }
  //添加 写入内容到BLE蓝牙设备状态监听
  static void addWriteMessageToBleDeviceListener(XFunctionWriteMessageToBleDeviceListener? listener){
    XBluetoothDeviceNotifyCallback.instance.addWriteMessageToBleDeviceListener(listener);
  }
  //删除 写入内容到BLE蓝牙设备状态监听
  static void removeWriteMessageToBleDeviceListener(XFunctionWriteMessageToBleDeviceListener? listener){
    XBluetoothDeviceNotifyCallback.instance.removeWriteMessageToBleDeviceListener(listener);
  }
  //添加 接收蓝牙BLE设备消息监听
  static void addReceiveBleDeviceMessageListener(XFunctionReceiveBleDeviceMessageListener? listener){
    XBluetoothDeviceNotifyCallback.instance.addReceiveBleDeviceMessageListener(listener);
  }
  //删除 接收蓝牙BLE设备消息监听
  static void removeReceiveBleDeviceMessageListener(XFunctionReceiveBleDeviceMessageListener? listener){
    XBluetoothDeviceNotifyCallback.instance.removeReceiveBleDeviceMessageListener(listener);
  }

  ///////////////////////////////////////////////////////////////////////////

  //连接设备ok
  static void _connectDevice(XBaseDevice baseDevice)
  {
    try{

      if(XStringUtils.isEmpty(baseDevice.bluetoothAddress)){
        return;
      }

      XLogUtils.printLog('---蓝牙设备正在连接中...');
      BluetoothDevice device=BluetoothDevice.fromId(baseDevice.bluetoothAddress!);

      XBleConnectApi connectApi=XBleConnectApi(
        bluetoothAddress:device.remoteId.str,
        device:device,
        baseDevice:baseDevice,
      );

      if(!bleConnectApiList.contains(connectApi)){
        connectApi.connect();
        bleConnectApiList.add(connectApi);
      }

      XLogUtils.printLog('---添加蓝牙设备连接, 总数量: ${bleConnectApiList.length}');

    }catch(e){
      XLogUtils.printLog('connectDevice报错: $e');
    }

  }


  //////////////////////////////////////////

  //处理写入消息成功 ok
  static void _handleWriteBluetoothDeviceSucceed(
      String? deviceName,
      String? bluetoothAddress,
      XBaseQueueMessage msg,
      )
  {

    //1.通知队列处理成功信息
    _queue?.handleSucceedMessageAndUnLockTempMessageQueue(msg.msgId);

    //
    if (msg.isHeartbeatCommand){
      //心跳包内部处理,不用发通知
      XLogUtils.printLog('---ble心跳数据写入成功: deviceName= $deviceName, bluetoothAddress= $bluetoothAddress',tag: 'XOther');
    }else{
      //本地蓝牙打印消息,通知外界
      XLogUtils.printLog("---ble msg写入成功: deviceName= $deviceName, bluetoothAddress= $bluetoothAddress, msgId=${msg.msgId}");
      //
      XBluetoothDeviceNotifyCallback.instance.writeMsgToBleDeviceCallback(
        isSuccess:true,
        deviceName:deviceName,
        bluetoothAddress:bluetoothAddress,
        msg:msg,
      );
    }

  }

  //处理写入消息失败 ok
  static void _handleWriteBluetoothDeviceFailed(
      String? deviceName,
      String? bluetoothAddress,
      String errorLog,
      XBaseQueueMessage msg,
      )
  {

    //1.通知队列处理失败信息
    _queue?.handleFailedMessageAndUnlockTempMessageQueue(msg.msgId,errorLog);

    //2.对外通知
    if (msg.isHeartbeatCommand){
      //心跳包内部处理,不用发通知
      XLogUtils.printLog('---ble心跳数据写入失败: deviceName= $deviceName, bluetoothAddress= $bluetoothAddress, errorLog=$errorLog',tag: 'XOther');
    }else{
      //本地蓝牙打印消息,通知外界
      XLogUtils.printLog('---ble msg写入失败: deviceName= $deviceName, bluetoothAddress= $bluetoothAddress,msgId=${msg.msgId}, errorLog=$errorLog');
      XBluetoothDeviceNotifyCallback.instance.writeMsgToBleDeviceCallback(
        isSuccess:false,
        deviceName:deviceName,
        bluetoothAddress:bluetoothAddress,
        msg:msg,
      );
    }
  }

}
